<script setup>
import {
  GetUserListByPage,
  ShowUserDetails,
  StopOrStartUser,
} from '@/api/customUser/customUser'
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useApp } from '@/pinia/modules/app'
import { debounce } from '@/utils'

const headers = {
  token: useApp().authorization.token, // 从pinia中获取token，在进行文件上传的时候将token设置到请求头中
}

// 表格数据模型
const list = ref([])

// 分页条数据模型
const total = ref(0)

// 定义搜索表单数据模型
const queryDto = ref({
  keyword: '',
  createTimeBegin: '',
  createTimeEnd: '',
})

const createTimes = ref([])

//分页数据
const pageParamsForm = {
  page: 1, // 页码
  limit: 3, // 每页记录数
}
const pageParams = ref(pageParamsForm)

// onMounted钩子函数
onMounted(() => {
  fetchData()
})

// 重置按钮点击事件处理函数
const resetData = () => {
  queryDto.value = {}
  createTimes.value = []
  //刷新页面
  fetchData()
}

const fetchData = async () => {
  if (createTimes.value.length == 2) {
    queryDto.value.createTimeBegin = createTimes.value[0]
    queryDto.value.createTimeEnd = createTimes.value[1]
  }

  console.log('查询页码', pageParams.value.page)
  console.log('查询页码限制', pageParams.value.limit)
  console.log('dto', queryDto.value)

  // 请求后端接口进行分页查询
  const { code, message, data } = await GetUserListByPage(
    pageParams.value.page,
    pageParams.value.limit,
    queryDto.value
  )
  console.log('data', data)

  list.value = data.records
  total.value = data.total

  console.log('得到的total', total.value)
}

// 搜索按钮点击事件处理函数防抖300毫米
// 该函数将在用户停止触发事件后的300毫秒（即0.3秒）后才执行fetchData函数。
// 如果在这段时间内用户再次触发事件，计时器会重新开始，直到用户停止触发事件为止
const debouncedSearchUser = debounce(fetchData, 300)
//重置按钮防抖
const debouncedResetData = debounce(resetData, 300)

// 对话框显示
const dialogVisible = ref(false)

const dislogForm = {
  avatar: '',
  username: '',
  nickName: '',
  sex: '',
  phone: '',
  memo: '',
  lastLoginIp: '',
  lastLoginTime: '',
  status: '',
  createTime: '',
}

const users = ref(dislogForm)

const userAddress = ref([])

//row是行对象,发起请求,打开对话框
//展示用户详情
const showUsers = async row => {
  //1.去后端查数据赋值
  const { code, message, data } = await ShowUserDetails(row.id)
  console.log(data)
  users.value = data.userInfo
  userAddress.value = data.userAddressList
  //2.打开对话框
  dialogVisible.value = true
}

const changeStatus = async row => {
  //判断状态,如果是1就变为0,如果是0就变为1,再重新赋值
  row.status = row.status == 1 ? 0 : 1

  const { code, message, data } = await StopOrStartUser(row.id, row.status)
  if (code === 200) {
    ElMessage.success('操作成功')
    fetchData()
  } else {
    ElMessage.error('操作失败')
  }
}
</script>

<template>
  <!---搜索表单-->
  <div class="search-div">
    <el-form label-width="70px" size="small">
      <el-row>
        <el-col :span="12">
          <el-form-item label="关键字">
            <el-input
              v-model.trim="queryDto.keyword"
              style="width: 100%"
              placeholder="用户名、呢称、手机号码"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="createTimes"
              type="daterange"
              range-separator="To"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="display:flex">
        <el-button type="primary" size="small" @click="debouncedSearchUser">
          搜索
        </el-button>
        <el-button size="small" @click="debouncedResetData">重置</el-button>
      </el-row>
    </el-form>
  </div>

  <el-dialog v-model="dialogVisible" title="详情" width="1100px">
    <!-- 分割线 -->
    <el-divider></el-divider>

    <el-form label-width="120px" title="基本信息">
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="头像">
            <img
              v-if="users.avatar"
              :src="users.avatar"
              class="avatar"
              width="50"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户名:">
            {{ users.username }}
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="昵称:">
            {{ users.nickName }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别:">
            {{ users.sex === 1 ? '男' : '女' }}
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="电话号码:">
            {{ users.phone }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注:">
            {{ users.memo }}
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="最后一次登录ip:">
            {{ users.lastLoginIp }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最后登录时间:">
            {{ users.lastLoginTime }}
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="状态">
            {{ users.status }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="创建时间">
            {{ users.createTime }}
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 分割线 -->
    <el-divider></el-divider>

    <!-- 地址信息 -->
    <div class="form-header">地址信息</div>
    <el-table :data="userAddress" border>
      <el-table-column property="tagName" label="地址标签" width="150" />
      <el-table-column property="isDefault" label="是否默认" width="200">
        <template #default="{ row }">
          {{ row.isDefault === 1 ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="详细收件地址">
        <template #default="{ row }">
          {{ row.name }} | {{ row.phone }} | {{ row.fullAddress }}
        </template>
      </el-table-column>
      <el-table-column property="createTime" label="创建时间" />
    </el-table>
  </el-dialog>

  <!---数据表格-->
  <el-table :data="list" style="width: 100%">
    <el-table-column prop="username" label="用户名" width="110" />
    <el-table-column prop="nickName" label="昵称" />
    <el-table-column prop="avatar" label="头像" #default="scope">
      <img :src="scope.row.avatar" width="50" />
    </el-table-column>

    <el-table-column prop="sex" label="性别" #default="scope" width="60">
      {{ scope.row.sex == 1 ? '男' : '女' }}
    </el-table-column>
    <el-table-column prop="phone" label="电话号码" width="126" />
    <el-table-column prop="lastLoginTime" label="最后登录时间" width="160" />
    <el-table-column prop="status" label="状态" #default="scope">
      {{ scope.row.status == 1 ? '正常' : '停用' }}
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间" width="180" />
    <el-table-column label="操作" align="center" width="180" #default="scope">
      <el-button type="primary" size="small" @click="showUsers(scope.row)">
        详情
      </el-button>
      <el-button
        :type="scope.row.status === 1 ? 'danger' : 'success'"
        size="small"
        @click="changeStatus(scope.row)"
      >
        {{ scope.row.status === 1 ? '停用' : '启用' }}
      </el-button>
    </el-table-column>
  </el-table>

  <el-pagination
    v-model:current-page="pageParams.page"
    v-model:page-size="pageParams.limit"
    :page-sizes="[10, 20, 50, 100]"
    @size-change="fetchData"
    @current-change="fetchData"
    layout="total, sizes, prev, pager, next"
    :total="total"
  />
</template>

<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
